﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using UDS.Components;

namespace UDS.SubModule.WorkAttendance
{
    /// <summary>
    /// DefaultPage 的摘要说明。
    /// </summary>
    public partial class DefaultPage : Page
    {
        // private bool DutyStatus = true;

        protected static string GetMemo(object id)
        {
            if (id.ToString() == "")
            {
                return "";
            }
            var db = new Database();
            SqlParameter[] prams = {
                Database.MakeInParam("@id", SqlDbType.BigInt, 8, Int64.Parse(id.ToString())),
                Database.MakeOutParam("@result", SqlDbType.NVarChar, 300)
            };
            db.RunProc("dbo.sproc_WA_GetMemo", prams);
            return (prams[1].Value.ToString());
        }

        protected static string GetTime(object day)
        {
            if (day.ToString() == "")
            {
                return "";
            }
            return (DateTime.Parse(day.ToString()).ToShortTimeString());
        }

        protected override void OnInit(EventArgs e)
        {
            btnCheckAttendance.Click += btnCheckAttendance_Click;
            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                int staffid = SiteContext.Current.UserID;

                DateTime now = DateTime.Now;
                StaffDutyTime dutyTime = WA_Setting.GetStaffDutyTime(staffid, now);

                if (dutyTime.ActualOffDutyTime != DateTime.MinValue && dutyTime.ActualOnDutyTime != DateTime.MinValue)
                {
                    lblDutyMessage.Text = "你已经完成了今天的考勤！";
                    btnCheckAttendance.Visible = false;
                }
                else if (dutyTime.ActualOnDutyTime == DateTime.MinValue)
                {
                    btnCheckAttendance.Text = "上班";
                    if (now.TimeOfDay > dutyTime.OnDutyTime.TimeOfDay)
                    {
                        // 迟到了 :(
                        lblDutyMessage.Text = "已经过了正常上班时间。请填写迟到的原因：";
                        txtAttendanceMemo.Visible = true;
                    }
                }
                else
                {
                    btnCheckAttendance.Text = "下班";
                    btnCheckAttendance.Attributes["onclick"] = "try{return(off_duty());}catch(ex){return false;}";
                    if (now.TimeOfDay < dutyTime.OffDutyTime.TimeOfDay)
                    {
                        // 早退 ?
                        lblDutyMessage.Text = "还未到下班时间。如果要下班，请填写适当的描述信息：";
                        txtAttendanceMemo.Visible = true;
                    }
                }

#if false
    //如果用户登陆并迟到
                if (Request.QueryString["notnormal"] != null)
                {
                    if ((Request.QueryString["login"] != null) && (Request.QueryString["login"] == "in"))
                    {
                        btnCheckAttendance.Text = "上班";
                        DutyStatus = true;
                        btnCheckAttendance.CommandArgument = "notnormal";
                        lblDutyMessage.Text = "上班迟到，请填写理由！";
                        txtAttendanceMemo.Visible = true;
                    }
                    else if ((Request.QueryString["login"] != null) && (Request.QueryString["login"] == "out"))
                    {
                        btnCheckAttendance.Text = "下班";
                        DutyStatus = false;
                        btnCheckAttendance.CommandArgument = "notnormal";
                        lblDutyMessage.Text = "下班早退，请填写理由！";
                        txtAttendanceMemo.Visible = true;
                    }
                }
                else //检查用户是否已经考勤
                {
                    var wd = new WA_Duty(SiteContext.Current.UserID);
                    if (wd.HaveCompletedDuty(DateTime.Now) == 0)
                    {
                        lblDutyMessage.Text = "你已经完成了今天的考勤！";
                        btnCheckAttendance.Visible = false;
                    }
                    else
                    {
                        if (!wd.HaveCheckedDuty(DateTime.Now))
                        {
                            btnCheckAttendance.Text = "上班";
                            DutyStatus = true;
                        }
                        else
                        {
                            btnCheckAttendance.Text = "下班";
                            DutyStatus = false;
                        }
                    }
                }
#endif

                // Display the current server time
                lbl_CurrentTime.Text = DateTime.Now.ToString("HH:mm:ss");

                //显示本星期的考勤数据
                GridBind();
            }
            else
            {
                btnCheckAttendance.Text = "正在处理。。。。";
            }

            base.OnLoad(e);
        }

        /// <summary>
        /// Display the working time information from Monday to Sunday in the current week.
        /// </summary>
        private void GridBind()
        {
            DateTime weekStartDate;
            DateTime weekEndDate;

            var now = DateTime.Now;
            /*
             * DayOfWeek:
             *  - Sunday: 0
             *  - Monday: 1
             *  ...
             *  - Saturday: 6
             */
            var day = now.DayOfWeek;
            if (day == DayOfWeek.Sunday)
            {
                weekStartDate = now.AddDays(-6);
                weekEndDate = now;
            }
            else
            {
                weekStartDate = now.AddDays((int)day - 1);
                weekEndDate = weekStartDate.AddDays(6);
            }

            DataTable table;
            var userId = SiteContext.Current.UserID;
            using (SqlDataReader dr = WA_Duty.GetStaffAttendanceData(weekStartDate, weekEndDate, new[] { userId }))
            {
                table = Tools.ConvertDataReaderToDataTable(dr);
            }
            grdWeekAttendanceData.DataSource = table.DefaultView;
            grdWeekAttendanceData.DataBind();
        }

        protected void btnCheckAttendance_Click(object sender, EventArgs e)
        {
            int userId = SiteContext.Current.UserID;
            DateTime now = DateTime.Now;
            StaffDutyTime dutyTime = WA_Setting.GetStaffDutyTime(userId, now);

            if (dutyTime.ActualOnDutyTime != DateTime.MinValue && dutyTime.ActualOffDutyTime != DateTime.MinValue)
            {
                lblDutyMessage.Text = "你已经完成了今天的考勤！";
                btnCheckAttendance.Visible = false;
            }
            else if (dutyTime.ActualOnDutyTime == DateTime.MinValue)
            {
                if (dutyTime.OnDutyTime.TimeOfDay < now.TimeOfDay)
                {
                    // 上班迟到
                    WA_Duty.RecordOnDutyData(userId, now, false, txtAttendanceMemo.Text);
                    lblDutyMessage.Text = "上班迟到了 :(";
                }
                else
                {
                    // 正常上班
                    WA_Duty.RecordOnDutyData(userId, now, true, null);
                    lblDutyMessage.Text = "正常上班没有迟到。考勤成功！";
                }
            }
            else
            {
                if (dutyTime.OffDutyTime.TimeOfDay > now.TimeOfDay)
                {
                    // 早退?
                    WA_Duty.RecordOffDutyData(userId, now, false, txtAttendanceMemo.Text);
                    lblDutyMessage.Text = "下班早退。考勤成功！";
                }
                else
                {
                    // 正常下班
                    WA_Duty.RecordOffDutyData(userId, now, true, null);
                    lblDutyMessage.Text = "正常下班。考勤成功！";
                }
            }
            btnCheckAttendance.Visible = false;
            txtAttendanceMemo.Visible = false;

#if false
            var wd = new WA_Duty(SiteContext.Current.UserID);
            //检查当天是否已经完成考勤
            int Duty = wd.HaveCompletedDuty(DateTime.Now);
            if (Duty == 0)
            {
                lblDutyMessage.Text = "你已经完成了今天的考勤！";
                btnCheckAttendance.Visible = false;
            }
            else
            {
                //检查是否迟到早退
                if (DutyStatus) //上班考勤
                {
                    if (((Button)(sender)).CommandArgument != "notnormal")
                    {
                        if (wd.CheckStatus(DutyAction.OnDuty))
                        {
                            wd.RecordOnDutyData(DateTime.Now, true, "").ToString();
                            lblDutyMessage.Text = "正常上班没有迟到。考勤成功！";
                            btnCheckAttendance.Visible = false;
                            DutyStatus = false;
                        }
                        else
                        {
                            lblDutyMessage.Text = "上班迟到，请填写理由！";
                            txtAttendanceMemo.Visible = true;
                            btnCheckAttendance.Text = "上班";
                            btnCheckAttendance.CommandArgument = "notnormal";
                        }
                    }
                    else
                    {
                        wd.RecordOnDutyData(DateTime.Now, false, txtAttendanceMemo.Text).ToString();
                        lblDutyMessage.Text = "上班迟到。考勤成功！";
                        txtAttendanceMemo.Visible = false;
                        btnCheckAttendance.Visible = false;
                        DutyStatus = false;
                        btnCheckAttendance.CommandArgument = "";
                    }
                }
                else //下班考勤
                {
                    if (((Button)(sender)).CommandArgument != "notnormal")
                    {
                        if (wd.CheckStatus(DutyAction.OffDuty))
                        {
                            wd.RecordOffDutyData(Duty, DateTime.Now, true, "");
                            lblDutyMessage.Text = "正常下班没有早退。考勤成功！";
                            btnCheckAttendance.Visible = false;
                            DutyStatus = true;
                        }
                        else
                        {
                            lblDutyMessage.Text = "下班早退，请填写理由！";
                            txtAttendanceMemo.Visible = true;
                            btnCheckAttendance.Text = "下班";
                            btnCheckAttendance.CommandArgument = "notnormal";
                        }
                    }
                    else
                    {
                        wd.RecordOffDutyData(Duty, DateTime.Now, false, txtAttendanceMemo.Text);
                        lblDutyMessage.Text = "下班早退。考勤成功！";
                        txtAttendanceMemo.Visible = false;
                        btnCheckAttendance.Visible = false;
                        DutyStatus = true;
                        btnCheckAttendance.CommandArgument = "";
                    }
                }
            }
#endif
            GridBind();
        }
    }
}